package org.dkd.helper;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;

import java.lang.reflect.Field;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.atomic.AtomicBoolean;

public class SpringBootRegister {

    private static final AtomicBoolean flag = new AtomicBoolean(false);
    private static final  Map<String, Object> FLOW_BEAN_MAP = new ConcurrentHashMap<>();

    public static void registerBean(String beanName, Object bean) {
        FLOW_BEAN_MAP.put(beanName, bean);
        if(flag.get()){
            refresh();
        }
    }

    public static Object getBean(String beanName) {
        return FLOW_BEAN_MAP.get(beanName);
    }

    public static<T> T getBean(Class<T> tclass) {
        return (T) FLOW_BEAN_MAP.get(tclass.getCanonicalName());
    }

    public static  void refresh() {
        flag.set(true);
        ApplicationContext applicationContext = (ApplicationContext) FLOW_BEAN_MAP.get("applicationContext");
        for (Object value : FLOW_BEAN_MAP.values()) {
            if (value instanceof Refreshable) {
                ((Refreshable) value).refresh(applicationContext);
            }
        }
    }
}
